package cn.middle.remote.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public final class GsonUtil {

	private GsonUtil() {
	}

	// gson实例
	private final static Gson GSON = new GsonBuilder().disableHtmlEscaping().create();

	/**
	 * 转换成 json
	 * @param data
	 * @return
	 */
	public static String toJson(Object data) {
		if(data != null) {
			return GSON.toJson(data);
		}
		
		return "";
	}
	
	/**
	 * 转成对象
	 * @param <T>
	 * @param json
	 * @param t
	 * @return
	 */
	public static <T> T toObject(String json,Class<T> t) {
		return GSON.fromJson(json,t);
	}
	
	/**
	 * 转成list
	 * @param <T>
	 * @param json
	 * @param t
	 * @return
	 */
	public static <T> List<T> toList(String json,Class<T> t){
        return GSON.fromJson(
                json,
                new TypeToken<List<T>>() {
                }.getType()
        );
	}
	
	/**
     * json 转成 特定的 rawClass<classOfT> 的Object
     *
     * @param json
     * @param classOfT
     * @param argClassOfT
     * @return
     */
    @SuppressWarnings("rawtypes")
	public static <T> T fromJson(String json, Class<T> classOfT, Class argClassOfT) {
        Type type = new ParameterizedType4ReturnT(classOfT, new Class[]{argClassOfT});
        return GSON.fromJson(json, type);
    }
    
    public static class ParameterizedType4ReturnT implements ParameterizedType {
        @SuppressWarnings("rawtypes")
		private final Class raw;
        private final Type[] args;
        @SuppressWarnings("rawtypes")
		public ParameterizedType4ReturnT(Class raw, Type[] args) {
            this.raw = raw;
            this.args = args != null ? args : new Type[0];
        }
        @Override
        public Type[] getActualTypeArguments() {
            return args;
        }
        @Override
        public Type getRawType() {
            return raw;
        }
        @Override
        public Type getOwnerType() {return null;}
    }

}
